package com.timeriver.data_preprocess

import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.stat.Correlation
import org.apache.spark.sql.{DataFrame, Dataset, Row, SparkSession}

/**
  * 相关性计算：比较变量间的相关性大小（0-1之间）
  *   数据源：mysql
  *   计算算子：spark ml Correlation算子
  *   要点：构建向量Vector
  */
object CorrelationDemo {
  def main(args: Array[String]): Unit = {
    val session: SparkSession = SparkSession.builder()
      .appName("数据相关性计算")
      .master("local[6]")
      .getOrCreate()

    val df: DataFrame = session.read
      .format("jdbc")
      .option("url", "jdbc:mysql://10.0.24.197:3306/ml_datasets")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("dbtable", "breast_cancer_wisconsin")
      .option("user", "root")
      .option("password", "123456")
      .load()

    /** 过滤缺失值 */
    val value: Dataset[Row] = df.filter(!_.anyNull)

    /** 获取特征列字段数组 */
    val inputCols: Array[String] = "clump_thickness,uniformity_of_cell_size,uniformity_of_cell_shape,marginal_adhesion,single_epithelial_cell_size,bare_nuclei,blan_chromatin,normal_nucleoli,mitoses".split(",")

    /** 构建特征列向量 */
    val data: DataFrame = new VectorAssembler()
      .setInputCols(inputCols)
      .setOutputCol("features")
      .transform(value)

    val pearson: DataFrame = Correlation.corr(data, "features")
    pearson.show(false)

    val spearman: DataFrame = Correlation.corr(data, "features", "spearman")
    spearman.show(false)
  }
}
